package LeetCode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class permutaions46 {
    public static void main(String[] args) {
        System.out.println(permute(new int[]{1, 2, 3}));
    }
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        int len = nums.length;
        if (len == 0) {
            return list;
        }
        ArrayDeque<Integer> path = new ArrayDeque<>();
        boolean[] used = new boolean[len];
        dfs(nums, len, 0, path, used, list);
        return list;
    }

    private static void dfs(int[] nums, int len, int depth, ArrayDeque<Integer> path, boolean[] used, List<List<Integer>> list) {
        if (len == depth) {
            list.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if(used[i]){
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            dfs(nums, len, depth+1, path, used, list);
            path.removeLast();
            used[i] = false;
        }
    }
}
